package monkey;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Test1 {
    // 共有100根香蕉
    private static final int TOTAL_BANANAS = 100;

    public static void main(String[] args) throws InterruptedException {
        AtomicInteger remainingBananas = new AtomicInteger(TOTAL_BANANAS);
        List<Monkey> monkeys = new ArrayList<>();

        // 创建3只猴子
        for (int i = 1; i <= 3; i++) {
            monkeys.add(new Monkey("Monkey " + i));
        }

        // 为每只猴子创建一个线程
        List<Thread> threads = new ArrayList<>();
        for (Monkey monkey : monkeys) {
            Thread thread = new Thread(() -> {
                while (remainingBananas.get() > 0) {
                    if (remainingBananas.getAndDecrement() > 0) {
                        monkey.grabBanana();
                    }
                }
            });
            threads.add(thread);
            thread.start();
        }

        // 等待所有线程结束
        for (Thread thread : threads) {
            thread.join();
        }

        // 按抢到香蕉的数量排序
        Collections.sort(monkeys, (m1, m2) -> m2.getBananas() - m1.getBananas());

        // 输出排行榜
        System.out.println("Final Ranking:");
        for (int i = 0; i < monkeys.size(); i++) {
            System.out.println((i + 1) + ". " + monkeys.get(i).getName() + " - " + monkeys.get(i).getBananas() + " bananas");
        }
    }

    static class Monkey {
        private String name;
        private int bananas;

        public Monkey(String name) {
            this.name = name;
            this.bananas = 0;
        }

        public void grabBanana() {
            bananas++;
        }

        public int getBananas() {
            return bananas;
        }

        public String getName() {
            return name;
        }
    }
}


